package com.wisdudu.blank.ui.setting;

import android.app.AlertDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.kelin.mvvmlight.base.ViewModel;
import com.kelin.mvvmlight.command.ReplyCommand;
import com.wisdudu.blank.R;
import com.wisdudu.blank.data.Injection;
import com.wisdudu.blank.data.bean.VersionInfo;
import com.wisdudu.blank.data.repo.UserRepo;
import com.wisdudu.blank.data.source.remote.client.retrofit.subscribers.ProgressSubscriber;
import com.wisdudu.blank.data.source.remote.client.retrofit.subscribers.SubscriberOnNextErrorListener;
import com.wisdudu.blank.support.util.AppUtil;
import com.wisdudu.blank.support.util.NetUtil;
import com.wisdudu.blank.support.util.ToastUtil;
import com.wisdudu.blank.support.widget.loading.LoadingProgressDialog;
import com.wisdudu.blank.ui.login.LoginActivity;
import com.wisdudu.blank.ui.setting.system.AboutUsActivity;
import com.wisdudu.blank.ui.setting.system.FeedBackFragment;
import com.wisdudu.blank.ui.user.ModifyPassFragment;

/**
 * Created by qyf on 2016/8/17.
 */

public class SettingVM implements ViewModel {
    private SettingFragment fragment;
    private UserRepo mUserRepo;

    public SettingVM(SettingFragment activity) {
        this.fragment = activity;
        mUserRepo = Injection.provideUserRepo();
    }

    public ReplyCommand onAboutUsClick = new ReplyCommand(() -> {
        Intent intent = new Intent(fragment.getActivity(), AboutUsActivity.class);
        fragment.startActivity(intent);
    });

    public ReplyCommand onFeedBackClick = new ReplyCommand(() -> {
        fragment.addFragment(new FeedBackFragment());
    });

    //退出登陆
    public ReplyCommand logout = new ReplyCommand(() -> {
        // TODO: 2016/8/31  退出登陆要清除的缓存注意在里面填写
        mUserRepo.logout();
        AppUtil.jumpActivity(fragment.getActivity(), LoginActivity.class);
        Intent intent = new Intent();
        intent.setAction("finishActivity");
        fragment.getActivity().sendBroadcast(intent);
        fragment.getActivity().finish();
    });
    public ReplyCommand onUpdateClcik = new ReplyCommand(() -> {
        String versionName = AppUtil.getPackageInfo(fragment.mActivity).versionName;
        int versionCode = AppUtil.getPackageInfo(fragment.mActivity).versionCode;
        mUserRepo.getVersion().compose(fragment.bindToLifecycle())
                .subscribe(new ProgressSubscriber<VersionInfo>(new SubscriberOnNextErrorListener<VersionInfo>() {
                    @Override
                    public void onError(Throwable e, LoadingProgressDialog pd) {
                        ToastUtil.INSTANCE.netError();
                    }

                    @Override
                    public void onNext(VersionInfo versionInfo, LoadingProgressDialog pd) {
                        if (versionInfo != null) {
                            if (Integer.parseInt(versionInfo.getVersions_id()) <= versionCode) {
                                ToastUtil.INSTANCE.toast("当前版本为最新版本" + versionName);
                            } else {
                                shopAlertDialog(versionInfo);
                            }
                        } else {
                            ToastUtil.INSTANCE.toast("当前版本为最新版本");
                        }
                    }
                }, fragment.getActivity(), "正在检查更新..."));
    });

    public ReplyCommand onUpdatePassClcik = new ReplyCommand(() -> {
        fragment.addFragment(new ModifyPassFragment());
    });

    public ReplyCommand onClearClcik = new ReplyCommand(() -> {
        clearCache();
    });

    private void clearCache() {
        LayoutInflater layoutInflater = LayoutInflater.from(fragment.mActivity);
        View view = layoutInflater.inflate(R.layout.dialog_delete, null);
        AlertDialog alertDialog = new AlertDialog.Builder(fragment.mActivity).setView(view).create();
        TextView tvTitle = (TextView) view.findViewById(R.id.tv_title);
        Button btn_confirm = (Button) view.findViewById(R.id.btn_confirm);
        Button btnCancel = (Button) view.findViewById(R.id.btn_cancel);
        tvTitle.setText("你确定要清理缓存吗？");
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();

                LoadingProgressDialog dialog = new LoadingProgressDialog(fragment.mActivity);
                dialog.setMessage("缓存清理中");
                dialog.show();
                Handler mHandler = new Handler();
                Runnable mRunnable = new Runnable() {
                    @Override
                    public void run() {
                        dialog.dismiss();
                    }
                };
                mHandler.postDelayed(mRunnable, 5000);
            }
        });
        alertDialog.show();
    }

    private void shopAlertDialog(VersionInfo versionInfo) {
        LayoutInflater layoutInflater = LayoutInflater.from(fragment.mActivity);
        View view = layoutInflater.inflate(R.layout.dialog_version, null);
        AlertDialog alertDialog = new AlertDialog.Builder(fragment.mActivity).setView(view).create();
        Button btn_confirm = (Button) view.findViewById(R.id.btn_confirm);
        TextView tv_version = (TextView) view.findViewById(R.id.tv_version);
        TextView tv_desc = (TextView) view.findViewById(R.id.tv_desc);
        ImageView iv_close = (ImageView) view.findViewById(R.id.iv_close);
        tv_version.setText("【" + versionInfo.getVersion() + "】 新版上线");
        tv_desc.setText(versionInfo.getDesc());
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                confirm(versionInfo, alertDialog);
            }
        });
        alertDialog.show();
    }

    private void confirm(VersionInfo versionInfo, AlertDialog alertDialog) {
        if (!NetUtil.INSTANCE.isConnected()) {
            ToastUtil.INSTANCE.toast("网络无连接,不可下载");
            return;
        }
        if (NetUtil.INSTANCE.isWifi(fragment.mActivity)) {
            toDownload(versionInfo);
        } else {
            alertDialog.dismiss();
            LayoutInflater layoutInflater = LayoutInflater.from(fragment.mActivity);
            View view = layoutInflater.inflate(R.layout.dialog_text_tips, null);
            AlertDialog updateAlertDialog = new AlertDialog.Builder(fragment.mActivity).setView(view).create();
            TextView tvCancel = (TextView) view.findViewById(R.id.tv_cancel);
            TextView tvConfirm = (TextView) view.findViewById(R.id.tv_confirm);
            tvCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    updateAlertDialog.dismiss();
                }
            });
            tvConfirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    toDownload(versionInfo);
                    updateAlertDialog.dismiss();
                }
            });
            updateAlertDialog.show();
        }
    }


    private void toDownload(VersionInfo versionInfo) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri content_url = Uri.parse(versionInfo.getUrl());
        intent.setData(content_url);
        fragment.startActivity(intent);
    }

}
